package com.delivery.deliverysystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.delivery.deliverysystem.common.ResponseCode;
import com.delivery.deliverysystem.common.ServerResponse;
import com.delivery.deliverysystem.dao.*;
import com.delivery.deliverysystem.exception.RException;
import com.delivery.deliverysystem.pojo.DAO.*;
import com.delivery.deliverysystem.pojo.DO.*;
import com.delivery.deliverysystem.pojo.VO.DefaultNameVO;
import com.delivery.deliverysystem.pojo.VO.DeliveryVO;
import com.delivery.deliverysystem.service.CommonService;
import com.delivery.deliverysystem.service.DeliveryService;
import com.delivery.deliverysystem.util.JWTUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【delivery(送货单表)】的数据库操作Service实现
* @createDate 2025-01-13 15:37:40
*/
@Service
@Slf4j
public class DeliveryServiceImpl extends ServiceImpl<DeliveryMapper, Delivery>
    implements DeliveryService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private DeliveryMapper deliveryMapper;

    @Autowired
    private DeliveryDetailMapper deliveryDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private DefaultNameMapper defaultNameMapper;

    @Autowired
    private NumberRuleMapper numberRuleMapper;

    @Autowired
    private CommonService commonService;


    @Override
    public String getCurrentUser() {
        String token = JWTUtil.getCurrentToken();
        if(token==null){
            log.warn("token为空");
            return null;
        }
        //获取出来的是用户代码
        String username = JWTUtil.getUsername(token);
        if(StringUtils.isBlank(username)){
            log.warn("用户代码为空");
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_code",username);
        try {
            User user = userMapper.selectOne(queryWrapper);
            if (user != null) {
                return user.getUsername();
            } else {
                log.warn("没有该用户代码的用户: {}", username);
                throw new RException(ResponseCode.EMPTY_ACCOUNT.getDesc(), ResponseCode.EMPTY_ACCOUNT.getCode());
            }
        } catch (Exception e) {
            log.error("从token获取用户时出错: {}", token, e);
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addDelivery(DeliveryDTO deliveryDTO) throws Exception{
        if(deliveryDTO == null) throw new RException("送货单信息不能为空", 500);
        String clientId = deliveryDTO.getClientId();
        if (StringUtils.isBlank(clientId)) throw new RException("客户编号不能为空", 500);
        QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
        clientQueryWrapper.eq("client_id",clientId);
        Client client = clientMapper.selectOne(clientQueryWrapper);
        if(client == null) throw new RException("客户不存在",500);
        LocalDateTime createDate = deliveryDTO.getCreateDate();

        //根据编号规则生成单号，累加流水号且生成后的单号不重复
        String deliveryId = generateDeliveryId(clientId,createDate);

        //订单号不能重复
        String orderId = deliveryDTO.getOrderId();
        if(!StringUtils.isBlank(orderId)){
            Delivery delivery1 = deliveryMapper.selectOne(new QueryWrapper<Delivery>().eq("order_id", orderId));
            if(delivery1 != null) throw new RException("订单号已存在",500);
        }
        List<DeliveryDetailDTO> productList = deliveryDTO.getProductList();
        if(productList.isEmpty()) throw new RException("产品列表不能为空",500);
        for (DeliveryDetailDTO deliveryDetailDTO : productList) {
                DeliveryDetail detail = DeliveryDetail.builder()
                        .deliveryId(deliveryId)
                        .productId(deliveryDetailDTO.getProductId())
                        .number(deliveryDetailDTO.getNumber())
                        .price(deliveryDetailDTO.getPrice())
                        .remark(deliveryDetailDTO.getRemark())
                        .discount(deliveryDetailDTO.getDiscount())
                        .singleWeight(deliveryDetailDTO.getSingleWeight())
                        .weight(deliveryDetailDTO.getWeight())
                        .color(deliveryDetailDTO.getColor())
                        .modelType(deliveryDetailDTO.getModelType())
                        .remark2(deliveryDetailDTO.getRemark2())
                        .remark3(deliveryDetailDTO.getRemark3())
                        .remark4(deliveryDetailDTO.getRemark4())
                        .remark5(deliveryDetailDTO.getRemark5())
                        .remark6(deliveryDetailDTO.getRemark6())
                        .remark7(deliveryDetailDTO.getRemark7())
                        .number2(deliveryDetailDTO.getNumber2())
                        .fileNum(deliveryDetailDTO.getFileNum())
                        .unit(deliveryDetailDTO.getUnit())
                        .singlePrice(deliveryDetailDTO.getSinglePrice())
                        .costPrice(deliveryDetailDTO.getCostPrice())
                        .category(deliveryDetailDTO.getCategory())
                        .productName(deliveryDetailDTO.getProductName())
                        .bladeMouldNumber(deliveryDetailDTO.getBladeMouldNumber())
                        .bladeMouldName(deliveryDetailDTO.getBladeMouldName())
                        .bladeTotalLength(deliveryDetailDTO.getBladeTotalLength())
                        .circleRadius(deliveryDetailDTO.getCircleRadius())
                        .rectangleLengthWidth(deliveryDetailDTO.getRectangleLengthWidth())
                        .alienLengthWidth(deliveryDetailDTO.getAlienLengthWidth())
                        .lineLength(deliveryDetailDTO.getLineLength())
                        .punchingHole(deliveryDetailDTO.getPunchingHole())
                        .bladeLength(deliveryDetailDTO.getBladeLength())
                        .bladeWidth(deliveryDetailDTO.getBladeWidth())
                        .bladeTemplateArea(deliveryDetailDTO.getBladeTemplateArea())
                        .locatingColumnCount(deliveryDetailDTO.getLocatingColumnCount())
                        .punchingHoleCount(deliveryDetailDTO.getPunchingHoleCount())
                        .screwHoleCount(deliveryDetailDTO.getScrewHoleCount())
                        .workPieceCount(deliveryDetailDTO.getWorkPieceCount())
                        .punchingHoleMeters(deliveryDetailDTO.getPunchingHoleMeters())
                        .text(deliveryDetailDTO.getText())
                        .allWork(deliveryDetailDTO.getAllWork())
                        .quotationForm(JSON.toJSONString(deliveryDetailDTO.getQuotationForm()))
                        .inspectionForm(JSON.toJSONString(deliveryDetailDTO.getInspectionForm()))
                        .label(JSON.toJSONString(deliveryDetailDTO.getLabel()))
                        .build();
                boolean detailInsertResult = deliveryDetailMapper.insert(detail) > 0;
                if (!detailInsertResult) {
                    log.error("插入送货单详情失败: {}", detail);
                    throw new RException("插入送货单详情失败", 500);
                }
            }

        Delivery add = Delivery.builder()
                .deliveryId(deliveryId)
                .clientId(clientId)
                .clientName(deliveryDTO.getClientName())
                .clientAddress(deliveryDTO.getClientAddress())
                .contact(deliveryDTO.getContact())
                .phone(deliveryDTO.getPhone())
                .department(deliveryDTO.getDepartment())
                .salesman(deliveryDTO.getSalesman())
                .orderId(orderId)
                .remark(deliveryDTO.getRemark())
                .deliveryDate(deliveryDTO.getDeliveryDate())
                .payMethod(deliveryDTO.getPayMethod())
                .status(0)//0未打印，1已打印，2已签回
                .styleNum(deliveryDTO.getStyleNum())
                .totalNum(deliveryDTO.getTotalNum())
                .totalPrice(deliveryDTO.getTotalPrice())
                .username(deliveryDTO.getUsername())
                .createDate(createDate)
                .fileName(deliveryDTO.getFileName())
                .companyId(getUserCompanyId())//与操作者的公司id一致
//                .companyId(1)//用作测试的公司id
                .build();
        deliveryMapper.insert(add);
        return deliveryId;
    }

    //送货单号由编号规则生成，获取当前的编号规则，流水号同一天就累加，第二天就重新开始。如果重复了就重新生成（继续累加）
    private String generateDeliveryId(String clientId, LocalDateTime createDate) {
        StringBuilder deliveryIdSb = new StringBuilder();
        List<NumberRule> numberRules = numberRuleMapper.selectList(null);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(timeFormat(numberRules));
        String time = createDate.format(formatter);
        int maxDeliveryIdNum = deliveryMapper.maxDeliveryIdNum(time);
        int yyyy = createDate.getYear();
        int yy = Integer.parseInt(String.valueOf(yyyy).substring(2));
        int mm = createDate.getMonthValue();
        int dd = createDate.getDayOfMonth();
        int currentNum = maxDeliveryIdNum + 1;
        String deliveryId;
        do {
            String num = String.format("%03d", currentNum);
            deliveryIdSb.setLength(0);  //清空sb
            for (NumberRule numberRule : numberRules) {
                if (numberRule.getStatus() == 1) {
                    switch (numberRule.getSymbol()) {
                        case "[CN]":
                            deliveryIdSb.append(clientId);
                            break;
                        case "[YYYY]":
                            deliveryIdSb.append(yyyy);
                            break;
                        case "[YY]":
                            deliveryIdSb.append(yy);
                            break;
                        case "[MM]":
                            deliveryIdSb.append(String.format("%02d",mm));
                            break;
                        case "[DD]":
                            deliveryIdSb.append(String.format("%02d",dd));
                            break;
                        case "[NUM]":
                            deliveryIdSb.append(num);
                            break;
                    }
                }
            }
            deliveryId = deliveryIdSb.toString();
            currentNum++;   //如果生成的单号重复了，就继续累加
        }while (deliveryMapper.selectById(deliveryId) != null);

        return deliveryId;
    }
    //根据编号规则生成时间格式
    private String timeFormat(List<NumberRule> numberRules){
        boolean entireYear = false;
        boolean shortYear = false;
        boolean month = false;
        boolean day = false;
        for(NumberRule numberRule : numberRules){
            if(numberRule.getStatus() == 1){
                switch (numberRule.getSymbol()){
                    case "[YYYY]":
                        entireYear = true;
                        break;
                    case "[YY]":
                        shortYear = true;
                        break;
                    case "[MM]":
                        month = true;
                        break;
                    case "[DD]":
                        day = true;
                        break;
                }
            }
        }
        if(entireYear && month && day) return "yyyyMMdd";
        else if(shortYear && month && day) return "yyMMdd";
        else if(entireYear && month) return "yyyyMM";
        else if(shortYear && month) return "yyMM";
        else if(entireYear && day) return "yyyydd";
        else if(shortYear && day) return "yydd";
        else if(month && day) return "MMdd";
        else if(entireYear) return "yyyy";
        else if(shortYear) return "yy";
        else if(month) return "MM";
        else if(day) return "dd";
        else throw new IllegalArgumentException("时间格式错误");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDelivery(DeliveryDTO deliveryDTO) throws Exception {
        if (deliveryDTO == null) throw new RException("送货单信息不能为空", 500);
        String deliveryId = deliveryDTO.getDeliveryId();
        if (StringUtils.isBlank(deliveryId)) throw new RException("送货单号不能为空", 500);
        Delivery existingDelivery = deliveryMapper.selectById(deliveryId);
        if (existingDelivery == null) throw new RException("送货单不存在", 500);
        //除了当前送货单，检查订单号是否重复
        String orderId = deliveryDTO.getOrderId();
        if(!StringUtils.isBlank(orderId)){
            QueryWrapper<Delivery> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("order_id", orderId).ne("delivery_id", deliveryId);
            Delivery existingOrder = deliveryMapper.selectOne(orderQueryWrapper);
            if (existingOrder != null) throw new RException("订单号已存在", 500);
        }
        String clientId = deliveryDTO.getClientId();
        if (StringUtils.isBlank(clientId)) throw new RException("客户编号不能为空", 500);
        QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
        clientQueryWrapper.eq("client_id", clientId);
        Client client = clientMapper.selectOne(clientQueryWrapper);
        if (client == null) throw new RException("客户不存在", 500);
        Delivery updatedDelivery = Delivery.builder()
                .deliveryId(deliveryId)
                .clientId(clientId)
                .clientName(deliveryDTO.getClientName())
                .clientAddress(deliveryDTO.getClientAddress())
                .contact(deliveryDTO.getContact())
                .phone(deliveryDTO.getPhone())
                .department(deliveryDTO.getDepartment())
                .salesman(deliveryDTO.getSalesman())
                .orderId(orderId)
                .remark(deliveryDTO.getRemark())
                .deliveryDate(deliveryDTO.getDeliveryDate())
                .payMethod(deliveryDTO.getPayMethod())
                .status(existingDelivery.getStatus()) //原有状态
                .username(deliveryDTO.getUsername())
                .createDate(existingDelivery.getCreateDate()) //原有创建日期
                .fileName(deliveryDTO.getFileName())
                .build();
        boolean updateResult = deliveryMapper.updateById(updatedDelivery) > 0;
        if (!updateResult) throw new RException("更新送货单失败", 500);

        List<DeliveryDetailDTO> productList = deliveryDTO.getProductList();
        if (productList == null || productList.isEmpty()) throw new RException("产品列表不能为空", 500);
        //删除现有的送货单详情，再插入新的产品
        QueryWrapper<DeliveryDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.eq("delivery_id", deliveryId);
        List<DeliveryDetail> deliveryDetails = deliveryDetailMapper.selectList(detailQueryWrapper);
        for(DeliveryDetail deliveryDetail : deliveryDetails){
            String quotationForm = deliveryDetail.getQuotationForm();
            QuotationFormDTO quotationFormDTO = JSON.parseObject(quotationForm, QuotationFormDTO.class);
            String image = quotationFormDTO.getImage();
            if(image != null && !image.isEmpty()) commonService.deleteFile(image);
        }
        deliveryDetailMapper.delete(detailQueryWrapper);

        for (DeliveryDetailDTO deliveryDetailDTO : productList) {
                DeliveryDetail detail = DeliveryDetail.builder()
                        .deliveryId(deliveryId)
                        .productId(deliveryDetailDTO.getProductId())
                        .number(deliveryDetailDTO.getNumber())
                        .price(deliveryDetailDTO.getPrice())
                        .remark(deliveryDetailDTO.getRemark())
                        .discount(deliveryDetailDTO.getDiscount())
                        .singleWeight(deliveryDetailDTO.getSingleWeight())
                        .weight(deliveryDetailDTO.getWeight())
                        .color(deliveryDetailDTO.getColor())
                        .modelType(deliveryDetailDTO.getModelType())
                        .remark2(deliveryDetailDTO.getRemark2())
                        .remark3(deliveryDetailDTO.getRemark3())
                        .remark4(deliveryDetailDTO.getRemark4())
                        .remark5(deliveryDetailDTO.getRemark5())
                        .remark6(deliveryDetailDTO.getRemark6())
                        .remark7(deliveryDetailDTO.getRemark7())
                        .number2(deliveryDetailDTO.getNumber2())
                        .fileNum(deliveryDetailDTO.getFileNum())
                        .unit(deliveryDetailDTO.getUnit())
                        .singlePrice(deliveryDetailDTO.getSinglePrice())
                        .costPrice(deliveryDetailDTO.getCostPrice())
                        .category(deliveryDetailDTO.getCategory())
                        .productName(deliveryDetailDTO.getProductName())
                        .bladeMouldNumber(deliveryDetailDTO.getBladeMouldNumber())
                        .bladeMouldName(deliveryDetailDTO.getBladeMouldName())
                        .bladeTotalLength(deliveryDetailDTO.getBladeTotalLength())
                        .circleRadius(deliveryDetailDTO.getCircleRadius())
                        .rectangleLengthWidth(deliveryDetailDTO.getRectangleLengthWidth())
                        .alienLengthWidth(deliveryDetailDTO.getAlienLengthWidth())
                        .lineLength(deliveryDetailDTO.getLineLength())
                        .punchingHole(deliveryDetailDTO.getPunchingHole())
                        .bladeLength(deliveryDetailDTO.getBladeLength())
                        .bladeWidth(deliveryDetailDTO.getBladeWidth())
                        .bladeTemplateArea(deliveryDetailDTO.getBladeTemplateArea())
                        .locatingColumnCount(deliveryDetailDTO.getLocatingColumnCount())
                        .punchingHoleCount(deliveryDetailDTO.getPunchingHoleCount())
                        .screwHoleCount(deliveryDetailDTO.getScrewHoleCount())
                        .workPieceCount(deliveryDetailDTO.getWorkPieceCount())
                        .punchingHoleMeters(deliveryDetailDTO.getPunchingHoleMeters())
                        .text(deliveryDetailDTO.getText())
                        .allWork(deliveryDetailDTO.getAllWork())
                        .quotationForm(JSON.toJSONString(deliveryDetailDTO.getQuotationForm()))
                        .inspectionForm(JSON.toJSONString(deliveryDetailDTO.getInspectionForm()))
                        .label(JSON.toJSONString(deliveryDetailDTO.getLabel()))
                        .build();
                boolean detailInsertResult = deliveryDetailMapper.insert(detail) > 0;
                if (!detailInsertResult) {
                    log.error("插入送货单详情失败: {}", detail);
                    throw new RException("插入送货单详情失败", 500);
                }
            }

        updatedDelivery.setStyleNum(deliveryDTO.getStyleNum());
        updatedDelivery.setTotalNum(deliveryDTO.getTotalNum());
        updatedDelivery.setTotalPrice(deliveryDTO.getTotalPrice());
        return deliveryMapper.updateById(updatedDelivery) > 0;
    }

    @Override
    public boolean deleteDelivery(String deliveryId) {
        if(StringUtils.isBlank(deliveryId)) return false;
        if(deliveryMapper.selectById(deliveryId)==null) return false;
        //删除送货单详情
        deliveryDetailMapper.delete(new QueryWrapper<DeliveryDetail>().eq("delivery_id",deliveryId));
        return deliveryMapper.deleteById(deliveryId)>0;
    }

    @Override
    public DeliveryVO getDeliveryById(String deliveryId) {
        if(StringUtils.isBlank(deliveryId)) return null;
        Delivery delivery = deliveryMapper.selectById(deliveryId);
        if(delivery==null) return null;
        List<DeliveryDetail> deliveryDetails = deliveryDetailMapper.
                selectList(new QueryWrapper<DeliveryDetail>().eq("delivery_id", deliveryId));
        List<DeliveryDetailDTO> detailVOList = new ArrayList<>();
        for(DeliveryDetail detail:deliveryDetails){
            DeliveryDetailDTO deliveryDetailDTO = new DeliveryDetailDTO();
            BeanUtils.copyProperties(detail,deliveryDetailDTO);
            //将json字符串转换为对象
            String inspectionForm = detail.getInspectionForm();
            if (inspectionForm != null) {
                deliveryDetailDTO.setInspectionForm(JSON.parseArray(inspectionForm, InspectionItemDTO.class));
            }
            String quotationForm = detail.getQuotationForm();
            if (quotationForm != null) {
                deliveryDetailDTO.setQuotationForm(JSON.parseObject(quotationForm, QuotationFormDTO.class));
            }
            String label = detail.getLabel();
            if (label != null) {
                deliveryDetailDTO.setLabel(JSON.parseObject(label, LabelDAO.class));
            }
            detailVOList.add(deliveryDetailDTO);
        }
        return DeliveryVO.builder()
                .deliveryId(delivery.getDeliveryId())
                .clientId(delivery.getClientId())
                .clientName(delivery.getClientName())
                .clientAddress(delivery.getClientAddress())
                .contact(delivery.getContact())
                .phone(delivery.getPhone())
                .department(delivery.getDepartment())
                .salesman(delivery.getSalesman())
                .orderId(delivery.getOrderId())
                .remark(delivery.getRemark())
                .deliveryDate(delivery.getDeliveryDate())
                .payMethod(delivery.getPayMethod())
                .status(delivery.getStatus())
                .styleNum(delivery.getStyleNum())
                .totalNum(delivery.getTotalNum())
                .totalPrice(delivery.getTotalPrice())
                .fileName(delivery.getFileName())
                .productList(detailVOList)
                .username(delivery.getUsername())
                .createDate(delivery.getCreateDate())
                .build();
    }

    @Override
    public IPage<Delivery> getDeliveryList(int pageNum, int pageSize) throws RException {
        //获取当前公司的所有送货单
        Page<Delivery> page = new Page<>(pageNum, pageSize);
        IPage<Delivery> deliveries = deliveryMapper.selectPage(page,
                new QueryWrapper<Delivery>()
                .eq("company_id",getUserCompanyId())
                .orderByDesc("create_date"));
        return deliveries;
    }

    @Override
    public List<Delivery> getTodayDeliveryList() throws RException {
        List<Delivery> deliveryList = deliveryMapper.selectList(new QueryWrapper<Delivery>()
                .eq("company_id",getUserCompanyId()));
        List<Delivery> result = new ArrayList<>();
        for(Delivery delivery:deliveryList){
            if(delivery.getCreateDate().toLocalDate().equals(LocalDateTime.now().toLocalDate())){
                result.add(delivery);
            }
        }
        return result;
    }

    //用来获取当前登录用户所在的公司id
    private int getUserCompanyId() throws RException {
        //获取当时登录的用户
        String token = JWTUtil.getCurrentToken();
        if(token==null){
            log.warn("token为空");
            throw new RException("未获取当前登录用户，token为空",500);
        }
        //获取出来的是用户代码
        String username = JWTUtil.getUsername(token);
        User operator = userMapper.selectOne(new QueryWrapper<User>().eq("user_code", username));
        if(operator==null) throw new RException("用户不存在",500);
        return operator.getCompanyId();
    }

    @Override
    public List<DefaultNameVO> getDisplayField() throws Exception {
        String userCode = JWTUtil.getCurrentUserCode();
//        String userCode = "user1";
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_code", userCode));
        String createDeliveryDisplay = user.getCreateDeliveryDisplay();
        List<DefaultNameVO> result = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        //json->map
        Map<String, Integer> displayMap = objectMapper.readValue(createDeliveryDisplay, new TypeReference<Map<String, Integer>>() {});
        //获取用户自己设置的字段
        String updateColumn = user.getUpdateColumn();
        Map<String, Object> ownName = objectMapper.readValue(updateColumn, new TypeReference<Map<String, Object>>() {});

        List<DefaultName> defaultNames = defaultNameMapper.selectList(null);
        for(DefaultName defaultName:defaultNames){
            String name = defaultName.getDefaultName();
            DefaultNameVO defaultNameVO = new DefaultNameVO();
            defaultNameVO.setDefaultName(name);
            //比较是否有用户设置的字段
            if(ownName.containsKey(name)){
                defaultNameVO.setDiyName(ownName.get(name).toString());
            }else{
                defaultNameVO.setDiyName(name);
            }
            //设置字段是否显示
            boolean isExist = false;
            for(Map.Entry<String, Integer> entry : displayMap.entrySet()){
                String displayName = entry.getKey().substring(2);
                if(displayName.equals(name)){
                    defaultNameVO.setIsShow(entry.getValue());
                    isExist = true;
                    break;
                }
            }
            //未找到则用默认
            if(!isExist){
                defaultNameVO.setIsShow(defaultName.getStatus());
            }
            result.add(defaultNameVO);
        }

        return result;
    }

    @Override
    public boolean updateDisplayField(FieldDisplayDTO displayDTO) throws Exception {
        if(displayDTO==null) return false;
        String userCode = JWTUtil.getCurrentUserCode();
//        String userCode = "user1";
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_code", userCode));
        ObjectMapper objectMapper = new ObjectMapper();
        //获取用户原来的字段
        String originalDeliveryStr = user.getCreateDeliveryDisplay();
        String originalProductStr = user.getProductDisplay();
        if(StringUtils.isBlank(originalDeliveryStr) || StringUtils.isBlank(originalProductStr)) return false;
        Map<String, Integer> originalDelivery = objectMapper.readValue(originalDeliveryStr, new TypeReference<Map<String, Integer>>() {});
        Map<String, Integer> originalProduct = objectMapper.readValue(originalProductStr, new TypeReference<Map<String, Integer>>() {});
        //获取用户设置的字段
        Map<String, Integer> deliveryDisplay = displayDTO.getDeliveryDisplay();
        Map<String, Integer> productDisplay = displayDTO.getProductDisplay();
        //开单界面字段显示
        for (Map.Entry<String, Integer> entry : deliveryDisplay.entrySet()) {
            String key = entry.getKey();
            //有要更新的字段则更新
            if(originalDelivery.containsKey(key)){
                originalDelivery.put(key, entry.getValue());
            }
        }
        //产品资料字段显示
        for (Map.Entry<String, Integer> entry : productDisplay.entrySet()) {
            String key = entry.getKey();
            if(originalProduct.containsKey(key)){
                originalProduct.put(key, entry.getValue());
            }
        }
        String newDeliveryStr = JSONObject.toJSONString(originalDelivery);
        String newProductStr = JSONObject.toJSONString(originalProduct);
        user.setCreateDeliveryDisplay(newDeliveryStr);
        user.setProductDisplay(newProductStr);

        return userMapper.updateById(user)>0;
    }

}